<template>
  <div class="menu-page">
    <transition name="el-zoom-in-top">
      <el-form v-show="searchMenuVisible" inline size="mini" :model="searchMenuForm" ref="searchMenuForm" @keyup.enter.native="searchMenuHandle">
        <el-form-item prop="word" label="菜单检索">
          <el-input v-model="searchMenuForm.word" placeholder="请输入检索的菜单名称" clearable></el-input>
        </el-form-item>
        <el-form-item prop="display">
          <el-select v-model="searchMenuForm.display" clearable placeholder="请选择显示状态" class="menu-status-input">
            <el-option label="显示" value="0"></el-option>
            <el-option label="隐藏" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="status">
          <el-select v-model="searchMenuForm.status" clearable placeholder="请选择菜单状态" class="menu-status-input">
            <el-option label="可用" value="0"></el-option>
            <el-option label="不可用" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button :disabled="loading" @click="searchMenuHandle" type="primary"
                     icon="el-icon-search">查询</el-button>
          <el-button :disabled="loading" @click="resetMenuPageHandle" plain
                     icon="el-icon-refresh-right">重置</el-button>
        </el-form-item>
      </el-form>
    </transition>

    <div class="m-tool">
      <el-button :disabled="loading" @click="openMenuDialogHandle(undefined, false, 0)"
                 type="primary" size="mini" plain icon="el-icon-plus">添 加</el-button>
      <el-button :disabled="loading" @click="openBatchMenuSaveDialogHandle"
                 type="success" size="mini" plain icon="el-icon-circle-plus-outline">批量添加</el-button>

      <!-- 还差一个刷新表格事件 -->
      <right-tool-bar :search-visible="searchMenuVisible" :search-load="loading"
                      @toggle-search="toggleSearch" @refresh-table="getMenuListHandle"  />
    </div>

    <el-table
      v-loading="dataLoad"
      element-loading-text="菜单列表加载中"
      element-loading-spinner="el-icon-loading"
      :data="menuList"
      row-key="menuId"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column prop="name" label="菜单名称" :show-overflow-tooltip="true" width="160"></el-table-column>
      <el-table-column prop="type" label="菜单类型" align="center" width="80">
        <template v-slot="scope">
          {{ scope.row.type === 0 ? '目录' : scope.row.type === 1 ? '菜单' : '按钮' }}
        </template>
      </el-table-column>
      <el-table-column prop="icon" label="图标" align="center" width="100">
        <template v-slot="scope">
          <svg-icon v-if="scope.row.icon" :icon-class="scope.row.icon" class="fz16" />
        </template>
      </el-table-column>
      <el-table-column prop="path" label="组件路径" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="permit" label="权限标识" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="sort" label="排序" align="center" width="60">
        <template v-slot="scope">
          <el-tag type="info" :class="'m-sort' + scope.row.type">
            {{ scope.row.sort }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="display" label="显隐" align="center" width="80">
        <template v-slot="scope">
          <el-tag v-if="scope.row.display !== undefined" type="info" :class="'m-display' + scope.row.display">
            {{ scope.row.display === 0 ? '显示' : '隐藏'  }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" align="center" width="80">
        <template v-slot="scope">
          <el-tag :type="scope.row.status === 0 ? 'primary' : 'danger'">
            {{scope.row.status === 0 ? '可用' : '停用'}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" align="center"></el-table-column>
      <el-table-column prop="createUser" label="创建用户" align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template v-slot="scope">
          <el-button v-if="scope.row.type !== 2" type="text" icon="el-icon-plus"
                     @click="openMenuDialogHandle(scope.row, false, scope.row.type + 1)">
            新增
          </el-button>
          <el-dropdown :disabled="loading">
            <span class="el-dropdown-link fz12" v-bind:style="{ color: themeColor, marginLeft: '7px' }">
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item icon="el-icon-s-operation"
                                @click.native="$refs.menuRoleRelationDialog.initDialog(scope.row)">
                关联角色
              </el-dropdown-item>
              <el-dropdown-item icon="el-icon-view" divided
                                @click.native="$refs.menuViewDialog.initDialog(scope.row.menuId)">
                查看
              </el-dropdown-item>
              <el-dropdown-item icon="el-icon-edit"
                                @click.native="openMenuDialogHandle(scope.row, true, undefined)">
                修改
              </el-dropdown-item>
              <el-dropdown-item v-show="scope.row.status === 1" icon="el-icon-check"
                                @click.native="updateMenuStatusHandle(scope.row, 0)">
                使用
              </el-dropdown-item>
              <el-dropdown-item v-show="scope.row.status === 0" icon="el-icon-close"
                                @click.native="updateMenuStatusHandle(scope.row, 1)">
                禁用
              </el-dropdown-item>
              <el-dropdown-item icon="el-icon-delete" @click.native="deleteMenuHandle(scope.row)">
                删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :disabled="dataLoad"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalNum"
      layout="total, sizes, prev, pager, next, jumper"
      class="paging">
    </el-pagination>

    <!-- 菜单添加/修改弹出框 -->
    <menu-save-update ref="menuDialog" @close-dialog="closeMenuDialogHandle" />

    <!-- 批量添加菜单弹出框 -->
    <batch-menu-save :dialog-visible="batchMenuSaveDialog" ref="batchMenuSave"
                 @close-batch-menu-save-dialog="closeBatchMenuSaveDialogHandle" />

    <!-- 菜单查看弹出框 -->
    <menu-view-dialog ref="menuViewDialog" />

    <!-- 菜单关联角色弹出框 -->
    <menu-role-relation-dialog ref="menuRoleRelationDialog" />

  </div>
</template>

<script>
  import RightToolBar from '@/components/common/right-toolbar'
  import MenuSaveUpdate from "@/components/menu/save-update/save-update.vue";
  import BatchMenuSave from "@/components/menu/save-update/batch-save.vue";
  import MenuViewDialog from '@/components/menu/view';
  import MenuRoleRelationDialog from '@/components/role/role-menu/relation.vue'

  export default {
    components: {
      RightToolBar, MenuSaveUpdate, BatchMenuSave, MenuViewDialog, MenuRoleRelationDialog
    },
    layout: 'admin',
    name: "admin-system-menu",
    data() {
      return {
        // 菜单数据列表
        menuList: [],
        // 菜单检索是否显示
        searchMenuVisible: true,
        // 菜单检索表单对象
        searchMenuForm: {
          // 菜单检索内容
          word: '',
          // 菜单显隐状态
          display: '',
          // 菜单类型
          common: '',
          // 菜单状态
          status: '',
        },
        // 当前展示页码
        pageIndex: 1,
        // 当前页显示个数
        pageSize: 10,
        // 当前菜单目录数量
        totalNum: 0,
        // 数据是否加载[false-不加载 true-加载]
        dataLoad: false,
        // 按钮是否可被点击[false-可以被点击 true-不可被点击]
        buttonLoad: false,
        // 菜单弹出框是否显示[true-显示 false-关闭]
        menuDialog: false,
        // 批量保存菜单数据弹出框是否显示[true-显示 false-关闭]
        batchMenuSaveDialog: false,
      }
    },
    // asyncData({ app, params, query}) {
    //   return app.$axios.$post('/sys/menu/list', { page: 1, limit: 10 })
    //     .then(data => {
    //       return {
    //         menuList: data.page.list,
    //         totalNum: data.page.totalNum
    //       }
    //     })
    // },
    computed: {
      // 主题颜色
      themeColor() {
        return this.$store.state.settings.theme
      },
      // 数据加载中
      loading() {
        return this.dataLoad || this.buttonLoad
      }
    },
    created() {
      if (process.client) {

        this.getMenuListHandle()
      }
    },
    methods: {
      // 菜单检索表单 显示/隐藏 事件
      toggleSearch() {
        this.searchMenuVisible = !this.searchMenuVisible
      },
      // 菜单检索事件
      searchMenuHandle() {
        this.pageIndex = 1;

        this.getMenuListHandle()
      },
      // 获取菜单数据列表事件
      getMenuListHandle() {
        let obj = {
          word: this.searchMenuForm.word,
          display: this.searchMenuForm.display,
          status: this.searchMenuForm.status,
          page: this.pageIndex,
          limit: this.pageSize
        }
        // 开始表格数据加载
        this.dataLoad = true;
        this.$axios.$post('/sys/menu/page/list', obj)
          .then(({ data:page }) => {
            this.menuList = page.list
            this.totalNum = page.totalNum
          })
          .catch(() => {})
          .finally(() => {
            // 表格数据加载结束
            this.dataLoad = false
          })
      },
      // 每页显示个数变化事件
      sizeChangeHandle(size) {
        this.pageIndex = 1
        this.pageSize = size
        this.getMenuListHandle()
      },
      // '点击特定页码'、'上一页'、'下一页'操作事件
      currentChangeHandle(index) {
        if (this.pageIndex === index) {
          return
        }
        this.pageIndex = index
        this.getMenuListHandle()
      },
      /**
       * 修改菜单状态事件
       * @param {Object} menu   菜单对象
       * @param {Number} status 最新状态值
       */
      updateMenuStatusHandle(menu, status) {
        // 按钮不可被点击
        this.buttonLoad = true;
        this.$axios.$post('/sys/menu/update/status', { menuId: menu.menuId, status: status })
          .then(() => {
            // 变更部门状态
            menu.status = status;
          })
          .catch(() => {})
          .finally(() => {
            // 按钮恢复可点击
            this.buttonLoad = false;
          })
      },
      // 删除菜单事件
      deleteMenuHandle(menu) {
        if (menu.children && menu.children.length > 0) {
          this.notify('warning', '温馨提示', `当前${menu.type === 0 ? '目录' : '路由'}菜单存在下级菜单，不可删除`);
          return
        }

        let typeTitle = menu.type === 0 ? '目录' : menu.type === 1 ? '路由' : '按钮'
        this.$confirm(`确定删除'${menu.name}'${typeTitle}菜单吗?`, '菜单删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 按钮不可被点击
          this.buttonLoad = true;
          this.$axios.$delete('/sys/menu/delete', { params: { menuId: menu.menuId }})
            .then(() => {
              this.notify('success', '操作成功', `删除‘${menu.name}’${typeTitle}菜单成功`);

              // 重新获取菜单列表
              this.getMenuListHandle()
            })
            .catch(() => {})
            .finally(() => {
              // 按钮恢复可点击
              this.buttonLoad = false;
            })
        }).catch(()=>{})
      },
      /**
       * 打开菜单操作弹出框事件
       * @param menu     菜单对象（添加子菜单或者修改菜单时使用）
       * @param optType  菜单操作类型（false-添加 true-修改）
       * @param menuType 添加类型（false-普通添加 true-子菜单添加）（只有添加菜单时可用）
       */
      openMenuDialogHandle(menu, optType, menuType) {
        this.$refs.menuDialog.initMenuDialog(menu, optType, menuType)
      },
      /**
       * 关闭菜单操作弹出框事件
       * @param {boolean} bool 是否刷新菜单列表
       */
      closeMenuDialogHandle(bool) {
        if (bool) {
          this.getMenuListHandle()
        }
      },
      /**
       * 打开菜单上传弹出框事件
       */
      openBatchMenuSaveDialogHandle() {
        this.batchMenuSaveDialog = true;

        this.$nextTick(() => {
          this.$refs.batchMenuSave.initBatchMenuSaveDialog();
        })
      },
      /**
       * 关闭菜单上传弹出框事件
       */
      closeBatchMenuSaveDialogHandle() {
        this.batchMenuSaveDialog = false;
      },
      // 重置页面事件
      resetMenuPageHandle() {
        let searchMenuForm = this.searchMenuForm
        if (searchMenuForm.word === '' && searchMenuForm.display === ''
          && searchMenuForm.common === '' && searchMenuForm.status === ''
          && this.pageIndex === 1 && this.pageSize === 10) {
          return
        }

        this.$refs.searchMenuForm.resetFields();
        this.pageIndex = 1
        this.pageSize = 10

        this.getMenuListHandle()
      }
    }
  }
</script>

<style scoped>
  .menu-page .menu-status-input {
    width: 140px;
  }
  .menu-page .m-tool {
    margin-bottom: 7px;
  }
  .menu-page .paging {
    float: right;
    margin: 7px;
  }
  .menu-page .m-sort0  {
    color: black;
  }
  .menu-page .m-sort1 {
    color: #ec5d0e;
  }
  .menu-page .m-sort2 {
    color: #0bc99c;
  }
  .menu-page .m-display0 {
    color: #6CBCBC;
  }
  .menu-page .m-display1 {
    color: #cba457;
  }

</style>
